import Vue from 'vue';
import API from '../../../api/api';

const state = {
    menu: null
};

const actions = {
    async getMenu({commit}, uval) {
        var url = API.MENU_URL;
        var res = await Vue.http.get(url);
        return res;
    },
    async addMenu({commit}, uval) {
        var res = await Vue.http.post(API.MENU_URL, uval);
        return res;
    },
    async updateMenu({commit}, uval) {
        var url = API.MENU_URL + uval.menuId;
        var res = await Vue.http.put(url, {
            menuName: uval.menuName,
            menuKey: uval.menuKey,
            menuType: uval.menuType,
            menuIcon: uval.menuIcon,
            menuUrl: uval.menuUrl,
            menuTarget: uval.menuTarget,
            display: uval.display,
            sort: uval.sort
        });
        return res;
    },
    async deleteMenu({commit}, uval) {
        var url = API.MENU_URL + uval.menuId;
        var res = await Vue.http.delete(url);
        return res;
    },
    async getMenuById({commit}, uval) {
        var url = API.MENU_URL + uval.menuId;
        var res = await Vue.http.get(url);
        return res;
    },
    async getMenuFuction({commit}, uval) {
        var url = API.MENU_URL + 'func/' + uval.menuId;
        var res = await Vue.http.get(url);
        return res;
    },
    async getOwnerMenu({commit}) {
        var url = API.MENU_URL + 'owner';
        var res = await Vue.http.get(url);
        if (res.code === '0000') {
            commit('SET_USER_MENU', JSON.stringify(res.data));
        }
        return res;
    }
};

const mutations = {
    SET_USER_MENU(state, token) {
        if (token) {
            sessionStorage.setItem('menu', token);
        } else {
            sessionStorage.removeItem('menu');
        }
    }
};

export default {
    state,
    actions,
    mutations
};